from PIL import Image,ImageDraw,ImageFont

class Visualizations:
    @staticmethod
    # def animatetracks(actors,width=640,height=480,colors=None,pw=6,ph=6,gif=False,delay=5):
    def animatetracks(tracks,actors,width=640,height=480,colors=None,pw=6,ph=6,gif=False,delay=5):
        if colors is None:
            colors = ["rgb(255,0,0)","rgb(0,255,0)","rgb(0,0,255)","rgb(255,255,0)","rgb(0,255,255)","rgb(255,0,255)","rgb(0,0,0)","rgb(255,255,255)","rgb(255,127,0)","rgb(255,0,127)","rgb(255,127,127)","rgb(127,255,0)","rgb(127,255,127)","rgb(0,255,127)","rgb(127,127,255)","rgb(127,0,255)","rgb(0,127,255)"]
        # tracks = [x.track for x in actors]
        xvals = []
        zvals = []
        tvals = []
        for track in tracks:
            for loc in track:
                # print loc
                xvals.append(loc[1][0])
                zvals.append(loc[1][1])
                tvals.append(loc[0])
        # print tvals
        minx = min(xvals)
        maxx = max(xvals)
        minz = min(zvals)
        maxz = max(zvals)
        mint = min(tvals)
        maxt = max(tvals)
        print minx,maxx,minz,maxz,mint,maxt
        xrat = float(width)/float(maxx-minx)
        zrat = float(height)/float(maxz-minz)
        iters = []
        tvals = []
        for track in tracks:
            i = iter(track)
            tvals.append(i.next())
            iters.append(i)
        plist = []
        # print tvals
        for t in range(mint,maxt+1):
            print "frame ",str(t)
            tlist = []
            ntvals = []
            for i,v in enumerate(tvals):
                print "tvals: ",tvals
                if v[0] == t:
                    tlist.append((i,v))
                    try:
                        ntvals.append(iters[i].next())
                    except StopIteration:
                        print "stopping iteration on frame "+str(t)
                        ntvals.append([0,[0,0]])
                elif v[0] > t:
                    ntvals.append(v)
                else:
                    ntvals.append(v)
            tvals = ntvals
            plist.append(tlist)
        print plist
        # sys.exit()
        ow = pw/2.
        oh = ph/2.
        font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf",12)
        cmd = "rm tempimages/*"
        os.system(cmd)
        for i,frame in enumerate(plist):
            if gif:
                fname = os.path.join(".","tempimages","{:05d}.gif".format(i))
            else:
                fname = os.path.join(".","tempimages","{:05d}.png".format(i))
            im = Image.new("RGB",(width,height),"rgb(127,127,127)")
            draw = ImageDraw.Draw(im)
            for loc in frame:
                print loc
                a = loc[0]
                color = colors[a]
                c = loc[1][1]
                x = (c[0]-minx)*xrat
                z = (c[1]-minz)*zrat
                ulx = x-ow
                ulz = z-ow
                brx = x+ow
                brz = z+ow
                coords = [(ulx,ulz),(brx,brz)]
                draw.rectangle(coords,fill=color)
                name = actors[a].name
                w,h = font.getsize(name)
                draw.rectangle([(brx,brz),(brx+w,brz+h)],fill="rgb(255,255,255)")
                draw.text((brx,brz),name,fill="rgb(0,0,0)",font=font)
            im.save(fname)
        if gif:
            cmd = "convert -delay "+str(delay)+" -loop 0 tempimages/*.gif tempimages/tracks.gif"
        else:
            cmd = "avconv -i tempimages/%5d.png -vcodec mpeg4 tempimages/tracks.mp4"
        os.system(cmd)
